var getDateFromJson = function (/*string*/dateString) {
    var subStr = dateString.replace("/Date(", "");
    var milliseconds = subStr.replace(")/", "");
    return new Date(parseInt(milliseconds));
};  // getDateFromJson

var getTodaysDate = function () {
    // find all events that are greater than todays date
    var todaysDate = new Date();

    var date = [];
    var year = todaysDate.getFullYear() + "";
    var month = todaysDate.getMonth() + 1 + "";
    var day = todaysDate.getDate() + "";

    var fDate = [];
    fDate.push(year);
    fDate.push("-");
    if (month.length === 1) {
        fDate.push("0");
    }
    fDate.push(month);
    fDate.push("-");
    if (day.length === 1) {
        fDate.push("0");
    }
    fDate.push(day);
    return fDate.join("");
};  // getTodaysDate

loadEvents = function (config) {

    config = config || {};
    var numResults = config.numResults || 1;

    OData.defaultHttpClient.enableJsonpCallback = true;

    /*"http://www.nerddinner.com/Services/OData.svc/Dinners" */
    /*"http://odata.netflix.com/v1/Catalog/Genres"*/
    /* boston azure
    https://odata.sqlazurelabs.com/OData.svc/v0.1/s3eqxeo3ba/bostonazure.org/Events?$format=json
    */

    var todaysDate = getTodaysDate();

    var uri = "https://odata.sqlazurelabs.com/OData.svc/v0.1/s3eqxeo3ba/bostonazure.org/Events";
    if (numResults == 1) {
        uri += "?$filter=start_utc%20gt%20datetime'" + todaysDate + "'";
        uri += "&$orderby=start_utc";
    } else {
        uri += "?$filter=start_utc%20lt%20datetime'" + todaysDate + "'";
        uri += "&$orderby=start_utc%20desc";
    }

    OData.read({ requestUri: uri,
        headers: { Accept: "application/json" }
    },
     function (data, request) {
         var results = data.results;
         var html = [];

         html.push('<ul data-role="list-view" data-inset="true" data-theme="c" data-dividertheme="b" style="{list-style-type:none}>');
         html.push('<li data-role="list-divider"></li>');
         var len = results.length;
         if (numResults === 'all') numResults = len;
         for (var i = 0; i < len; i++) {
             var title = results[i].title;
             var formattedDate = getDateFromJson(results[i].start_utc);
             html.push("<li><div data-role='content' data-theme='d'><div class='date'>" + formattedDate + "</div><div class='title'>" + results[i].title + "</div>");
             if (numResults === 1) {
                 html.push("<div class='description'>" + results[i].description_html + "</div>");
             }
             html.push("</li>");
         }
         html.push("</div></ul>");
         config.loadHandler.call(this, html.join());
     },
	   function (err) { alert("Error occurred " + err.message); }
	 );

};


